package com.yeyks.commonReference.service.config.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.utils.ObjectConvertUtil;
import com.yeyks.commonReference.service.config.RechargeConfigService;
import com.yeyks.config.dal.dao.RechargeConfigMapper;
import com.yeyks.config.dal.domain.RechargeConfig;
import com.yeyks.config.dto.RechargeConfigDTO;
import com.yeyks.consumer.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


/**
 * <p>
 * 充值配置表 服务实现类
 * </p>
 *
 * @author yun
 * @since 2019-06-25
 */
@Service
public class RechargeConfigServiceImpl extends ServiceImpl<RechargeConfigMapper, RechargeConfig> implements RechargeConfigService {

    @Autowired
    private UserInfoService userInfoService;

    private QueryWrapper<RechargeConfig> setCommonConfiguration(QueryWrapper<RechargeConfig> queryWrapper, Integer userId, Integer type) {
        return queryWrapper
                .eq(RechargeConfig.STATUS, 1)
                .eq(RechargeConfig.TYPE, type)
                .eq(Objects.equals(type, 2), RechargeConfig.USER_TYPE, userInfoService.getById(userId).getType());
    }

    /**
     * 通过充值金额获取赠送金额
     *
     * @param payAmount
     * @param type
     * @return
     */
    @Override
    public RechargeConfig getByPayAmount(Integer userId, Integer payAmount, Integer type) {
        return baseMapper.selectOne(
                setCommonConfiguration(new QueryWrapper<RechargeConfig>(), userId, type)
                        .eq(RechargeConfig.PAY_AMOUNT, payAmount)
        );
    }

    /**
     * 通过类型查询充值金额字段列表
     *
     * @param type
     * @return
     */
    @Override
    public List<RechargeConfigDTO> list(Integer userId, Integer type) {
        List<RechargeConfig> rechargeConfigs = baseMapper.selectList(
                setCommonConfiguration(new QueryWrapper<RechargeConfig>(), userId, type)
        );
        return ObjectConvertUtil.convertList(rechargeConfigs, RechargeConfigDTO.class);
    }


    /**
     * 根据用户和卡类型还有支付金额查询套餐是否存在
     *
     * @param userId
     * @param type
     * @param payAmount
     * @return
     */
    @Override
    public RechargeConfig checkPackage(Integer userId, Integer type, Integer payAmount) {
        RechargeConfig rechargeConfig = getOne(
                setCommonConfiguration(new QueryWrapper<RechargeConfig>(), userId, type)
                        .eq(RechargeConfig.PAY_AMOUNT, payAmount)
                        .last("limit 1")
        );
        if (Objects.isNull(rechargeConfig)) {
            throw new ServiceException("充值套餐不存在");
        }
        return rechargeConfig;
    }

}
